package com.biqee.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class PasswordUtil {
	public static final int DEFAULT_LEN = 8;
	
	private static final String ALGORITHM = "MD5";
	
	/**
	 * 生成随机字符串
	 * @param length：字符串长度，如果length 小于 DEFAULT_LEN 则 返回长度为DEFAULT_LEN 的字符串
	 * @return
	 */
	public static String genRandomString(int length) {
		if(length <= DEFAULT_LEN) {
			return genRandomStr(DEFAULT_LEN);
		} else {
			return genRandomStr(length);
		}
	}

	/**
	 * 使用md5加密
	 * @param plainPass
	 * @return
	 */
	public static String encryptedByMD5(String plainPass) {
		String salt = EnvUtil.getUserPassSalt();
		String plainPassFinal = salt + plainPass + salt;
		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance(ALGORITHM);
			messageDigest.update(plainPassFinal.getBytes());
			byte[] b = messageDigest.digest();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < b.length; i++) {
				int val = ((int) b[i]) & 0xff;
				if (val < 16)
					sb.append("0");
				sb.append(Integer.toHexString(val));
			}
		     return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("encrypt failed. ", e);
		}
	}

	private static final char[] STR_CANDIDATES = {
		'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
		'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
		'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',  
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	
	private static String genRandomStr(int len) {
		final int maxNum = 36;
		int i; 
		int count = 0; 

		StringBuilder pwd = new StringBuilder("");
		Random r = new Random();
		while (count < len) {
			i = Math.abs(r.nextInt(maxNum));
			if (i >= 0 && i < STR_CANDIDATES.length) {
				pwd.append(STR_CANDIDATES[i]);
				count++;
			}
		}
		
		return pwd.toString();
	}
	
}
